package cn.chiship.sdk.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lijian
 */
public class UrlUtil {

	private static final String SEMICOLON = ";";

	private UrlUtil() {
	}

	/**
	 * 组装UTL
	 * @param url
	 * @param queries
	 * @return 结果
	 * @throws UnsupportedEncodingException
	 */
	public static String buildUrl(String url, Map<String, Object> queries) throws UnsupportedEncodingException {
		StringBuilder sbUrl = new StringBuilder();
		sbUrl.append(url);
		if (null != queries) {
			StringBuilder sbQuery = new StringBuilder();
			for (Map.Entry<String, Object> query : queries.entrySet()) {
				if (0 < sbQuery.length()) {
					sbQuery.append("&");
				}
				if (StringUtil.isNullOrEmpty(query.getKey()) && !StringUtil.isNull(query.getValue())) {
					sbQuery.append(query.getValue());
				}
				if (!StringUtil.isNullOrEmpty(query.getKey())) {
					sbQuery.append(query.getKey());
					if (!StringUtil.isNull(query.getValue())) {
						sbQuery.append("=");
						sbQuery.append(URLEncoder.encode(StringUtil.getString(query.getValue()), "utf-8"));
					}
				}
			}
			if (0 < sbQuery.length()) {
				if (analyticUrlMap(url).isEmpty()) {
					sbUrl.append("?").append(sbQuery);
				}
				else {
					sbUrl.append("&").append(sbQuery);
				}
			}
		}
		PrintUtil.console("构建组装后的URL：" + sbUrl);
		return sbUrl.toString();
	}

	public static Map<String, String> analyticUrlMap(String url) {
		Map<String, String> params = new HashMap<>(2);
		url = url.replace("?", ";");
		if (!url.contains(SEMICOLON)) {
			return params;
		}
		if (url.split(SEMICOLON).length > 0) {
			String[] arr = url.split(SEMICOLON)[1].split("&");
			for (String s : arr) {
				String[] values = s.split("=");
				if (values.length >= 2) {
					params.put(values[0], values[1]);
				}

			}
		}
		return params;
	}

	public static List<String> analyticUrlList(String url) {
		List<String> paramsValue = new ArrayList<>();
		url = url.replace("?", SEMICOLON);
		if (!url.contains(SEMICOLON)) {
			return paramsValue;
		}
		if (url.split(SEMICOLON).length > 0) {
			String[] arr = url.split(SEMICOLON)[1].split("&");
			for (String s : arr) {
				String value = s.split("=")[1];
				paramsValue.add(value);
			}
		}
		return paramsValue;
	}

}
